﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNet.Common.NHibernateUtil;
using NHibernate;

namespace ZLCMS.Web.Tools
{
    public partial class DownloadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["filepath"]) && !string.IsNullOrEmpty(Request["filename"]))
            {
                DownloadFunc(Request["filepath"], Request["filename"]);
            }
        }


        public void DownloadFunc(string filepath, string fileName)
        {
            System.IO.Stream iStream = null;

            byte[] buffer = new Byte[10240];

            int length;

            long dataToRead;

            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (!filepath.ToLower().Contains("/upload/qrcode/"))
                    {
                        Response.Write("<script>alert('禁止访问')</script>");
                        iStream.Close();
                        Response.End();
                    }
                    filepath = Server.MapPath("~/" + filepath); 

                    iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    Response.Clear();

                    dataToRead = iStream.Length;

                    long p = 0;
                    if (Request.Headers["Range"] != null)
                    {
                        Response.StatusCode = 206;
                        p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
                    }
                    if (p != 0)
                    {
                        Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
                    }
                    Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(fileName + ".jpg")));

                    iStream.Position = p;
                    dataToRead = dataToRead - p;

                    while (dataToRead > 0)
                    {
                        if (Response.IsClientConnected)
                        {
                            length = iStream.Read(buffer, 0, 10240);

                            Response.OutputStream.Write(buffer, 0, length);
                            Response.Flush();

                            buffer = new Byte[10240];
                            dataToRead = dataToRead - length;
                        }
                        else
                        {
                            dataToRead = -1;
                        }
                    }
                }
                catch
                {
                    Response.Write("<script>alert('文件不存在')</script>");
                    if (iStream != null)
                    {
                        iStream.Close();
                    }
                }
            }
        }
    }
}